<template>
  <div v-if="visible" class="modal-overlay">
    <div class="modal-card">
      <button class="close-btn" @click="emitClose">×</button>
      <h2 class="title">确认支付</h2>
      <div class="content">
        <p><strong>用户名：</strong>{{ userName }}</p>
        <p>
          <strong>支付金额：</strong><span class="price">￥{{ price }}</span>
        </p>
        <p v-if="balance !== null"><strong>当前余额：</strong>￥{{ balance }}</p>
        <p v-else class="loading-text">正在加载余额...</p>
      </div>
      <div class="actions">
        <button class="btn pay-btn" :disabled="isPaying || balance === null" @click="handlePay">
          {{ isPaying ? '支付中...' : '立即支付' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps<{
  visible: boolean
  userName: string
  price: number
  trainNumber?: string
  seatType?: string
  date?: string
  passengerName?: string
  passengerIdCard?: string
}>()
const emits = defineEmits(['close', 'success', 'fail'])
const balance = ref<number | null>(null)
const isPaying = ref(false)

watch(
  () => props.visible,
  (val) => {
    if (val) fetchBalance()
  },
)
async function fetchBalance() {
  try {
    const res = await fetch(
      `http://localhost:9000/api/users?username=${encodeURIComponent(props.userName)}`,
    )
    if (!res.ok) {
      if (res.status === 404) {
        throw new Error('用户不存在，请重新登录')
      }
      throw new Error('获取用户信息失败')
    }
    const data = await res.json()
    // 从用户对象中提取余额字段
    balance.value = data.balance || 0
  } catch (e) {
    console.error('余额获取失败', e)
    balance.value = 0
    // 如果是用户不存在，直接显示错误
    if (e instanceof Error && e.message.includes('用户不存在')) {
      emits('fail', { status: 'user_not_found', message: e.message })
      emitClose()
    }
  }
}
function emitClose() {
  emits('close')
}
async function handlePay() {
  if (balance.value === null) return
  if (balance.value < props.price) {
    emits('fail', { status: 'insufficient_balance' })
    emitClose()
    return
  }

  // 只进行余额验证，不创建订单
  // 订单创建由父组件处理
  emits('success', {
    status: 'ok',
    balance: balance.value,
    price: props.price,
  })
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-card {
  background-color: #fff;
  border-radius: 16px;
  padding: 24px;
  width: 360px;
  position: relative;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  text-align: center;
  animation: fadeIn 0.3s ease;
}

.close-btn {
  position: absolute;
  top: 12px;
  right: 16px;
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.title {
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.content p {
  margin: 10px 0;
  font-size: 16px;
  color: #555;
}

.price {
  color: #e53935;
  font-weight: bold;
  font-size: 18px;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.actions {
  margin-top: 20px;
}

.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 15px;
  cursor: pointer;
}

.pay-btn {
  background-color: #2196f3;
}

.btn:disabled {
  background-color: #aaa;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
